package com.ebocy.hammer.core.socket;

import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.write.WriteRequest;

import com.ebocy.hammer.core.init.MessageLoader;
import com.ebocy.hammer.core.log.EbocyLogManager;
import com.ebocy.hammer.core.message.AbstractC2SMessage;

public class MessageFilter extends IoFilterAdapter {
	private static Logger logger = EbocyLogManager.getSystemLogger();
	public static long receive_num = 0;
	public static long send_num = 0;

	@Override
	public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
		IoBuffer buffer = (IoBuffer) message;
		short messageCode = buffer.getShort();
		// System.out.println(session.getId()+"####################"+messageCode);
		Class<AbstractC2SMessage> class1 = MessageLoader.getReceiveMessageByCode(messageCode);
		if (class1 == null) {
			logger.error("此消息号" + messageCode + "在初始化消息中找不到！buffer==" + buffer);
		} else {
			AbstractC2SMessage receiveMessage = class1.newInstance();
			receiveMessage.setIoBuffer(buffer);
			receiveMessage.readMessage();
			receive_num++;
			super.messageReceived(nextFilter, session, receiveMessage);
		}
	}

	@Override
	public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception {
		if (writeRequest.getMessage() instanceof IoBuffer) {
			send_num++;
			super.filterWrite(nextFilter, session, writeRequest);

		}
	}
}
